<template>
  <!-- 管理岗位弹窗 -->
  <a-modal @cancel="handleClose" title="绑定岗位" :visible="visibleJob" width="1200px" destroyOnClose>
    <a-row :gutter="10">
      <!-- 侧边栏 -->
      <a-col :span="6" class="tree-wrapper">
        <!-- 公司组织树搜索 -->
        <tree-organization
          ref="treeOrganization"
          :expandByAuto="true"
          :selectedKeys.sync="selectedKeys"
          :selectOptions.sync="selectOptions"
          :org-query="{ baseOrgType: 0, containVirtual: '',enable: 1 }"
          :showChildWithSearch="true"
          :filterFn="handleFilterTree"
          @loader="getJobs"
          :isTypes="true"
        />
      </a-col>
      <!-- 主内容 -->
      <a-col :span="18">
        <a-spin :spinning="loadingState.isInitJobs">
          <a-transfer :data-source="leftJobs" :target-keys="rightJobs" :render="(item) => item.title" @change="handleChange" />
        </a-spin>
        <div class="bindPost">
          <h4 style="margin-top: 6px; margin-left: -10px">主岗位：</h4>
          <a-select v-model="mainPostId" :class="isDisabled" :options="cacheList" placeholder="请选中" style="width: 40%"></a-select>
        </div>
      </a-col>
      <!-- <a-col :span="24" :push="9" style="margin-top: 20px">
        <a-col :span="5">
          <h4 style="margin-top: 6px; margin-left: -10px">主岗位：</h4>
        </a-col>
        <a-col :span="6" :pull="1">
          <a-select v-model="mainPostId" :options="cacheList" size="middle" placeholder="Please select" style="width: 108%"></a-select>
        </a-col>
      </a-col> -->
    </a-row>
    <template slot="footer" style="text-align: right">
      <a-button class="ml12" type="default" @click="handleClose">取消</a-button>
      <a-button :loading="loading" type="primary" @click="handleSubmitPost">提交</a-button>
    </template>
  </a-modal>
</template>

<script>
import { getPostPNameByUser, userMainPost } from '@/api/commons.js'
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { bindUserOrg } from '@/api/system/system'
import { getJobs } from '@/api/subassembly/TreeSelectOrganization'
import { postChangeLog } from '@/mixin/mixin'

export default {
  name: 'a' + Date.now(),
  mixins: [postChangeLog],
  components: {
    TreeOrganization
  },
  props: {
    // 显隐控件
    visibleJob: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loadingState: {
        isInitJobs: false // 加载岗位
      },
      key: '',
      selectedKeys: {},
      selectOptions: {},
      loading: false,
      leftJobs: [],
      rightJobs: [],
      postRightJobs: [],
      formModel: {},
      cacheList: [],
      mainPostId: '', //可选择岗位选中的数据
      options: [], //可选择岗位
      isDisabled: '' //是否必填
      //   isDisabled:'postJob',//是否必填
    }
  },
  methods: {
    handleFilterTree(data) {
      return data.label !== '分包商' && data.label !== '分公司'
    },
    /**
     * 获取用户的岗位信息
     */
    async getUserMainPost() {
      let res = await userMainPost(this.form.userId)
      let { status, data } = res
      if (status === 200) {
        this.mainPostId = data.mainPostId
      }
    },
    /**
     * 获取用户的岗位信息
     */
    async getPostPNameByUserReq() {
      this.loadingState.isInitJobs = true
      try {
        const params = {
          userId: this.formModel.userId
        }
        const res = await getPostPNameByUser(params)
        this.loadingState.isInitJobs = false
        const list = res.data || []
        this.leftJobs = list.map((item) => {
          return {
            key: item.id,
            title: item.pname + '/' + item.name,
            disabled: false,
            isRight: true,
            enable: item.enable
          }
        })
        this.rightJobs = this.leftJobs.map((item) => item.key)
        this.cacheList = JSON.parse(JSON.stringify(this.leftJobs))
        this.mainPostId = res.data.some((item) => item.isMainPost == 1) ? res.data.find((item) => item.isMainPost == 1).id : ''
      } catch (e) {
        this.loadingState.isInitJobs = false
        console.error(e)
      }
    },
    handleClose() {
      this.$emit('handleCancel', false)
    },
    getJobs() {
      this.loadingState.isInitJobs = true
      getJobs({ orgId: this.selectedKeys[0] })
        .then((res) => {
          this.loadingState.isInitJobs = false
          const resultList = res.data || []
          // 添加原本leftJobs没有的岗位
          this.leftJobs = [...this.cacheList]
          let leftArr = resultList
            .filter((item) => {
              return !this.leftJobs.includes(item.id)
            })
            .map((item) => {
              return {
                key: item.id,
                title: item.pname || item.name,
                disabled: item.enable != 1,
                enable: item.enable,
                isRight: false
              }
            })
          this.leftJobs = [...this.leftJobs, ...leftArr]
        })
        .catch((e) => {
          console.error(e)
          this.loadingState.isInitJobs = false
        })
    },
    handleChange(targetKeys, direction, moveKeys) {
      this.rightJobs = targetKeys
      this.leftJobs.forEach((item) => {
        if (!targetKeys.includes(item.key)) {
          item.isRight = false
          item.disabled = item.enable != 1
        }
      })
      // 保留已选中到右边的数据
      this.cacheList = this.leftJobs.filter((item) => {
        return targetKeys.includes(item.key)
      })
    },
    handleSubmitPost() {
      if (this.loading) {
        return
      }
      if (!this.mainPostId && !!this.rightJobs.length) {
        this.$message.warning('请选择主岗位')
        return
      }
      this.loading = true
      let params = {
          id: this.formModel.id,
          mainPostId: this.mainPostId,
          posts: this.rightJobs.map((key) => {
            return {
              id: key
            }
          })
        },
        that = this
      bindUserOrg(params)
        .then((res) => {
          this.loading = false
          this.handleClose()
          this.$emit('confirm', res.data)
          //获取一周内岗位变更数量
          that.handleGetPostsChangeLog()
        })
        .catch((err) => {
          this.loading = false
        })
    }
  },
  watch: {
    visibleJob(val) {
      if (!val) {
        this.leftJobs = []
        this.rightJobs = []
        this.postRightJobs = []
        this.mainPostId = ''
        return
      }
      this.$nextTick(() => {
        this.getPostPNameByUserReq()
        this.$refs.treeOrganization.getList().then(() => {
          this.getJobs()
        })
      })
    },
    form: {
      immediate: true,
      handler(val) {
        if (val) {
          this.mainPostId = val.mainPostId || ''
        }
        if (Object.keys(val).length !== 0) {
          this.formModel = val
        }
      }
    },
    leftJobs() {
      this.$nextTick(() => {
        if (!document.querySelectorAll('.LazyLoad') && !document.querySelectorAll('.LazyLoad').length) return
        document.querySelectorAll('.LazyLoad').forEach((item) => {
          if (item.hasAttribute('style')) {
            item.removeAttribute('style')
          }
        })
      })
    },
    rightJobs(val) {
      if (val.length>0){
        this.isDisabled = 'postJob'
      }else {
        this.isDisabled = ''
        this.mainPostId = ''
      }
      this.$nextTick(() => {
        if (!document.querySelectorAll('.LazyLoad') && !document.querySelectorAll('.LazyLoad').length) return
        document.querySelectorAll('.LazyLoad').forEach((item) => {
          if (item.hasAttribute('style')) {
            item.removeAttribute('style')
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .ant-transfer-list {
  width: 45% !important;
  height: 400px !important;
  .ant-transfer-list-content-item-text {
    display: inline-block;
    width: calc(100% - 18px);
    white-space: break-spaces;
  }
  .ant-checkbox-wrapper {
    vertical-align: top;
  }
}
@{deep} .tree-wrapper {
  height: calc(var(--heightVh) * 0.6);
  & > div,
  & > div > div {
    height: 100%;
  }
  .treeBox {
    height: calc(100% - 40px) !important;
  }
}
.bindPost {
  margin-top: 15px;
  display: flex;
  justify-content: end;
  transform: translateX(-5%);
}
.postJob {
  /deep/.ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
}
</style>
